package cn.conac.rc.ofs.mq.service;

import java.io.Serializable;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.jms.config.JmsListenerContainerFactory;
import org.springframework.jms.config.SimpleJmsListenerContainerFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;

import cn.conac.rc.ofs.mq.converter.ObjMessageConverter;

@Component
public class MqSendService {
	
    @Autowired
    ConfigurableApplicationContext context;
    
	@Bean
    JmsListenerContainerFactory<?> myJmsContainerFactory(ActiveMQConnectionFactory connectionFactory) {
        SimpleJmsListenerContainerFactory factory = new SimpleJmsListenerContainerFactory();
        connectionFactory.setTrustAllPackages(true);
        factory.setConnectionFactory(connectionFactory);
        return factory;
    }
	
    public Integer SendMessage(String mqName,final Serializable obj ){
    	 Integer ret = 0;
    	 JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class);
    	 ObjMessageConverter objMessageConverter = new ObjMessageConverter();
    	 jmsTemplate.setMessageConverter(objMessageConverter);
    	 Session session;
    	 Destination destination;
		try {
			session = jmsTemplate.getConnectionFactory().createConnection().createSession(true, Session.AUTO_ACKNOWLEDGE);
			destination = session.createQueue(mqName);
			 jmsTemplate.convertAndSend(destination, obj);
		} catch (JMSException e) {
			e.printStackTrace();
			ret = -1;
		}
		return ret;
    }
}
